/**
 * @author NORGUET Thibaud
* ADD @author BOURGEOIS Mehdi
*/


function JS2V_activationUpload(){
    var cmd = "SendMessage 'Level' 'activationUpload' ";
    document.Virtools.DoCommand(cmd);
}

function JS2V_sendURL(){
    var _url = _global_url+"images/" + _global_nom;
    var cmd = "SetAttribute '" + _global_nom + "' 'saveURL' '" + _url + "'";
    document.Virtools.DoCommand(cmd);
    V2JS_Message(_url);
}


///////////////////////////////////////////////////////
//-- Importation de l'image dans l'environement 3D --//
///////////////////////////////////////////////////////

function JS2V_uploadSucceed(_nom, _id){
   _global_nom = _nom;

    var cmd = "SendMessage 'Level' 'uploadSucceed' ";
    document.Virtools.DoCommand(cmd);
    JS2V_sendName(_id);
}


function JS2V_uploadFailed(){
    var cmd = "SendMessage 'Level' 'uploadFailed' ";
    document.Virtools.DoCommand(cmd);
}


function JS2V_sendName(_id){
    var cmd = "SetAttribute '3dFrame_attribute' 'saveName' '" + _global_nom + "'";
    document.Virtools.DoCommand(cmd);
    var cmd = "SetAttribute '3dFrame_attribute' 'saveID' '" + _id + "'";
    document.Virtools.DoCommand(cmd);
    var _url = _global_url+"images/" + _global_nom;
    var cmd = "SetAttribute '3dFrame_attribute' 'saveURL' '" + _url + "'";
    
    document.Virtools.DoCommand(cmd);
    V2JS_Message(_global_nom);
}


///////////////////////////////
//-- MESSAGE From Virtools --//
///////////////////////////////

function V2JS_Message(_message){
    document.getElementById("upload_message").innerHTML += " " + _message + "<br />";
}

//fonction de sauvegarde des positions d'une image qui viens d'etre mise sur l'environnement virtool
function V2JS_getImagePosition(_position){
    var _tab = _position.split('!');
    
    V2JS_Message(_position);
    $.ajax({
        type: "POST",
        url: "./php/saveImagePosition.php",
        data: "position=" + _tab[0] + "&dir=" + _tab[1] + "&up=" + _tab[2] + "&id=" + _tab[3] + "&id_user=" + _global_id_user,
        success: function(_msg){
            V2JS_Message("return getPos : " + _msg);
        }
    });
}

function JS2V_logout(){
    var cmd = "SendMessage 'Level' 'logout' ";
    document.Virtools.DoCommand(cmd);
}

//fonction appeler toute les x secondes pour avoir les images à proximité!
function V2JS_currentPosition(_position){
    $.ajax({
        type: "POST",
        url: "./php/getImagePosition.php",
        data: "position=" + _position,
        success: function(){
            var cmd = "SendMessage 'Level' 'written' ";
            document.Virtools.DoCommand(cmd);
        }
    });
}

function V2JS_lastPosition(_position){
    var _tab = _position.split('!');
    V2JS_Message(_position);
    $.ajax({
        type: "POST",
        url: "./php/saveLastPosition.php",
        data: "position=" + _tab[0] + "&dir=" + _tab[1] + "&up=" + _tab[2] + "&pseudo=" + _global_nom,
        success: function(_msg){
            V2JS_Message("return getPos : " + _msg);
        }
    });
}

function JS2V_visiteur(){
	
    var cmd = "SendMessage 'Level' 'visiteur' ";
    document.Virtools.DoCommand(cmd);
    $.ajax({
        type: "POST",
        url: "./php/getPublicImage.php",
    });
   
    
}



function imagesPrivees_update(){
//	console.log('imagesPrivees_update');
	//var cmd = "SendMessage 'Level' 'imagesPrivees_update'";
	//var cmd = "SendMessage 'Level' 'login'";
   	//var cmd = "SendMessage 'Level' 'imagesPrivees_received'";
//	document.Virtools.DoCommand(cmd);	
}



/////////////////////
//   LOGIN LOGIN   //
/////////////////////

function JS2V_login(){

	JS2V_AttributePostionUser(); // Il a besoin de cette fonction on ne sait pourquoi ?
	var cmd = "SendMessage 'Level' 'login'";
	var loginResult = document.Virtools.DoCommand(cmd);


	// Inscription de la caméro utilisateur
    $.getJSON("./php/getPositionUser.php", {
        "id_user": _global_id_user
    }, function(_json){
		console.log('ecriture fichier user sucess')
    });				
			
			
	// Recuperation des cameras utilisateurs				
    $.getJSON("./php/getUserImage.php", {
        "id_user": _global_id_user
    }, function(_json){
    
        var _html = "";
        
        //----------- addon florent di bartolo -----------------------------------//
        //array for as3 gallery
        var ar_as = "";
        ar_as += "[";
        
        for (var _i = 0; _i < _json.length; _i++) {
        
        	var privacy =	_json[_i]['droit'];
        	var img_id = 	_json[_i]['id_image'];
        	var img_name =	_json[_i]['nom_image']
        	var user_id = _global_id_user;
        	
        	ar_as +="["
        	ar_as += img_id;
        	ar_as += ",";
        	ar_as += img_name;
        	ar_as += ",";
        	ar_as += privacy;
        	ar_as += ",";
        	ar_as += user_id;
        	ar_as +="],";
        	//---------- addon florent di bartolo ----------------------------//
    
            
        }
        
        //---------- addon florent di bartolo ----------------------------//
		ar_as = ar_as.substring(0, ar_as.length-1);        
        ar_as +="]";
        getFlashMovie("myFlashBoard").sendTextToBoard(1, ar_as);
        sendToActionScript('1', ar_as);
//        V2JS_Message(ar_as);
        //---------- addon florent di bartolo ----------------------------//
        
    });    
}

// LOGIN TEST
function V2JS_Login_Ready() {
	// Level Login
   	var cmd = "SendMessage 'Level' 'login'";
    var loginResult = document.Virtools.DoCommand(cmd);
    V2JS_Message('V2JS_Login_Ready dans Javascript');
}

//-----------------------
//ENVOIE LES POSITIONS DE L'UTILISATEUR - A SUPPRIMER ? - Envoie de requetes en double 
function JS2V_AttributePostionUser(){

	    $.getJSON("./php/getStartPosition.php", {
	        "id_user": _global_id_user
	    }, function(_json){

			// Envoie des positions de l'utilisateur 
			
	        	var cmd = "SetAttribute '3dFrame_attribute' 'positionCamera' '" + _json['position_cam'] + "'";
				var ResultpositionCamera = document.Virtools.DoCommand(cmd);
				V2JS_Message('ResultpositionCamera = ' + ResultpositionCamera);

	            cmd = "SetAttribute '3dFrame_attribute' 'orientationDir' '" + _json['orientation_dir'] + "'";
	            var ResultorientationDir = document.Virtools.DoCommand(cmd);
				V2JS_Message('ResultorientationDir = ' + ResultorientationDir);

	            cmd = "SetAttribute '3dFrame_attribute' 'orientationUp' '" + _json['orientation_up'] + "'";
	            var ResultorientationUp = document.Virtools.DoCommand(cmd);
				V2JS_Message('ResultorientationUp = ' + ResultorientationUp);
				
				var cmd = "SendMessage 'Level' 'login'";
				var loginResult = document.Virtools.DoCommand(cmd);

	    });
}


function _changeDroit(_id){
    //var _id = $.(_param).attr('id');
    $.ajax({
        type: "POST",
        url: "./php/changeImageDroit.php",
        data: "id_image=" + _id,
    });
}

function ajaxFileUpload(){

    $.ajaxFileUpload({
        url: './ajaxfileupload/doajaxfileupload.php',
        secureuri: false,
        fileElementId: 'fileToUpload',
        dataType: 'json',
        success: function(data, status){
            if (typeof(data.error) != 'undefined') {
                if (data.error != '') {
                   alert(data.error);
					
                    JS2V_uploadFailed();
                    
                    //addon !!!!
                    V2JS_Message("JS2V_uploadFailed();");
                    
                }
                else
                {                          	                   
                    V2JS_Message(data.nom+" "+data.id+" "+_global_id_user);
                    sendToActionScript(2, data.nom, data.id, _global_id_user);                   
                }
            }
        },
        error: function(data, status, e){
            alert(e);
        }
    });
    
    return false;
    
}

function _identification(_login){
	
	$.getJSON("./php/identification.php", {
            "login": _login
        }, function(_json){
			
            if (_json != "") {
                var v_html = "";
               
                document.getElementById('formulaire').style.display = "block";
                _global_id_user = _json['id_user'];
				setTimeout("JS2V_login()", 3000);
				
            }
			else{
				document.getElementById("content").innerHTML += "<br /> Erreur d'identification";
			}
            
            
        });
}



function f_sendPassMail(){
    var _email = document.getElementById('email').value;
    $.ajax({
        type: "POST",
        url: "./php/sendPassMail.php",
        data: "email=" + _email,
        success: function(_msg){
		document.getElementById('id_mail').innerHTML += _msg;
        }
    });
}



function f_verif_form(nom_input){

    if (document.getElementById(nom_input).value == "") {
        document.getElementById(nom_input).style.backgroundColor = "#F99";
    }
    else {
        document.getElementById(nom_input).style.backgroundColor = "white";
    }
}

function f_save_compte(){

    var tab = new Array;
    var _login = $("#login").val();
    var _pass = $("#pass").val();
    var _mail = $("#mail").val();
    
    
    if (document.getElementById("login").value == "") {
        tab.push("x");
        document.getElementById("login").style.backgroundColor = "#F99";
    }
    if (document.getElementById("pass").value == "") {
        tab.push("x");
        document.getElementById("pass").style.backgroundColor = "#F99";
    }
    if (document.getElementById("mail").value == "") {
        tab.push("x");
        document.getElementById("mail").style.backgroundColor = "#F99";
    }
    
    if (tab.length == 0) {
        $.ajax({
            type: "POST",
            url: "./php/saveCompte.php",
            data: "login=" + _login + "&pass=" + _pass + "&mail=" + _mail,
            success: function(_msg){
               
                document.getElementById("new_compte").innerHTML += "<br />" + _msg;
            }
        });
    }
    else {
        return false;
        
    }
    
}

function changeVitesse(_speed){
	var cmd = "SetAttribute '3dFrame_attribute' 'vitesse' '" + _speed + "'";
    document.Virtools.DoCommand(cmd);
	if (_speed == 20) {
		var _html = '<input type="button" onclick="changeVitesse(2);" value="x2" />';
	}
	else{
		var _html = '<input type="button" onclick="changeVitesse(20);" value="x2" />';
	}
	$("#vitesse").html(_html);
}
